package com.coding.controller;

import com.alibaba.fastjson.JSON;
import com.coding.dto.RestBean;
import com.coding.pojo.VideoCommentReply;
import com.coding.pojo.VideoCommentReplyRelate;
import com.coding.pojo.VideoComments;
import com.coding.pojo.Videos;
import com.coding.service.VideoMessageService;
import com.coding.service.VideoService;
import com.coding.util.CommentInitializer;
import com.coding.utils.AliyunOSSUtil;
import com.coding.vo.VideoStorageData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/video")

public class VideoController {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private VideoService videoService;

    @Autowired
    VideoMessageService videoMessageService;

    @Autowired
    CommentInitializer initializer;

    @Resource
    RedisTemplate<String, Object> MyRedis;


    @PostMapping("/uploadVideo")
    public RestBean uploadVideo(@RequestParam("video") String videoInfoJson,
                                MultipartRequest request) {

        try {
            Videos video = new ObjectMapper().readValue(videoInfoJson, Videos.class);

            // 创建一个列表来收集URL
            List<String> urlList = new ArrayList<>();

            MultiValueMap<String, MultipartFile> files = request.getMultiFileMap();

            for (String key : files.keySet()) {
                List<MultipartFile> fileList = files.get(key);
                for (MultipartFile file : fileList) {
                    String fileName = file.getOriginalFilename();
                    String fileUrl = aliyunOSSUtil.uploadFile(file, fileName);

                    // 将URL添加到列表
                    urlList.add(fileUrl);
                }
            }

            // 拼接URL，使用逗号作为分隔符
            String concatenatedUrl = String.join(",", urlList);

            // 设置到video对象的url属性
            video.setUrl(concatenatedUrl);

            // 保存视频信息到数据库
            RestBean result = videoService.addVideo(video);
            System.out.println("上传结果：" + result);

            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return new RestBean(400, "上传失败", null); // 返回上传失败的信息

        }
    }


    @Scheduled(fixedRate = 360000)
    public void refreshVideoData(){
        System.out.println("获取最新的视频信息");
        VideoInitializer();
    }

    @PostConstruct
    public void VideoInitializer() {
        System.out.println("服务启动，视频开始初始化");

//        初始化方法
        List<Videos> list = videoService.init();
        List<Videos> temp = new ArrayList<>();

        for (Videos video : list) {

            video.setLikes(videoService.likesInit(video.getId()) + 1);

            video.setShares(videoService.sharesInit(video.getId()) + 1);

            video.setFavourites(videoService.favouriteInit(video.getId()) + 1);

//            video.setFan(videoService.isFan(video.getUserId()));

            temp.add(video);


        }

        list.clear();

        List<VideoComments> commentList = videoMessageService.initComments();

        List<VideoCommentReply> replyList = videoMessageService.initReplies();

        List<VideoCommentReplyRelate> relateList = videoMessageService.initRelates();

//        打印视频信息（存入redis）
        List<VideoStorageData> dataList = initializer.initializer(temp, commentList, relateList, replyList);

        for (VideoStorageData current : dataList) {
//            System.out.println("\n\n\n\n");
//            System.out.println(dataList.get(i));
//            System.out.println("\n\n\n\n");
            Object jsonData = JSON.toJSON(current);
            String key = JSON.toJSONString(current.getVideoId());
//            MyRedis.opsForList().rightPush("VideoList", jsonData);
            MyRedis.opsForHash().put("VideoMap", current.getVideoId() + " ", jsonData);

        }
        System.out.println(MyRedis.opsForHash().values("VideoMap"));
    }

    @RequestMapping("/getVideoData")
    public RestBean getVideoData(Long userId) {
        System.out.println("userId: " + userId);
        System.out.println("获取视频信息");
//        获取所有视频
        List<Object> videoData = new ArrayList<>();
        Set<Object> keySet = MyRedis.opsForHash().keys("VideoMap");
        if (MyRedis.opsForHash().size("VideoMap") > 5) {
            for (Object key : keySet) {
                System.out.println(key);
                System.out.println(MyRedis.opsForHash().get("VideoMap",key));
                videoData.add(MyRedis.opsForHash().get("VideoMap",key));
            }
        }else{
            videoData = MyRedis.opsForHash().values("VideoMap");
        }

//        根据用户的常用标签进行推荐（推荐算法）
        System.out.println(videoData);

        return RestBean.success(videoData);
    }

    @RequestMapping("/getNewVideoData")
    public RestBean getNewVideos() {

        return null;
    }

}
